package com.gcxy.tour.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gcxy.tour.common.CommException;
import com.gcxy.tour.domain.UserInfo;
import com.gcxy.tour.service.UserService;


/**
 * 注册功能
 * @author 方昆
 *
 */
@WebServlet(urlPatterns= {"/register.do"})
public class RegisterServlet extends HttpServlet{
	
	

	private static final long serialVersionUID = 714696102643206099L;

	private Logger logger=LoggerFactory.getLogger(getClass());
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.debug("执行dopost方法");
		//1.提取信息
		try {
				String usercode=req.getParameter("usercode");
				String password=req.getParameter("password");
				String username=req.getParameter("username");
				String confirm=req.getParameter("confirm");
				UserInfo user=new UserInfo(usercode, username, password);
				user.setPassword(password);
				user.setUsercode(usercode);
				user.setUsername(username);
				
				UserService userService=new UserService();
				// 2.数据类型转换
				logger.debug("数据类型转换");
				
				
				// 3.校验数据
				if(  usercode!=null && usercode.trim().length()>0 
						&& password!=null && password.trim().length()>0 
						&& username!=null && username.trim().length()>0 
						&& confirm!=null && confirm.trim().length()>0 
						&& confirm.equals(password)) {
					logger.debug("校验成功");
				}else {					
					throw new CommException();
				}
				//4.业务处理:持久化数据
				
				userService.register(user);
				
				
				//用来保存当前登录用户的信息，可以在当前用户的所有页面使用
				HttpSession session=req.getSession();
				
					//5.记录session信息
					session.setAttribute("usercode", usercode);
					session.setAttribute("usertype", user.getUsertype());
					//6.跳转到成功页面
					req.getRequestDispatcher("/login.jsp").forward(req, resp);
					
		       }catch( CommException e){
					
					
					req.setAttribute("error","登录失败，账号或密码长度必须大于0");
					//6.跳转到失败页面
					req.getRequestDispatcher("/register.jsp").forward(req, resp);
					}
		
	
	}


		@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	
		doGet(req, resp);
	}

}
